/* eslint-disable array-callback-return */
'use strict';

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

const Service = require('egg').Service;
class GoodsService extends Service {
  // 获取所有商品列表
  async index(data) {
    try {
      const { Goods, GoodsPhoto, Classify } = this.app.model.Tables.Shop;

      const query = this.ctx.query;
      // 每页多少条
      const limit = parseInt(query.limit) || 10;
      // 页数
      const page = parseInt(query.page) || 1;
      // 页数 * 每页个数
      const offset = limit * (page - 1);

      const str_status = this.ctx.query.status; ///获取前端传过来的状态码
      //对状态码进行处理
      let arr_status;
      if (str_status == undefined || str_status == '') {
        arr_status = null;
        //如果前端没有传或者传递一个空的status
        //就默认显示所有状态的商品
      } else {
        arr_status = str_status.split(',');
        //前端传了状态码，只显示对应状态码的商品
      }
      const where = {
        status: arr_status || [0, 1, 2],
        //传递则显示状态码为arr_status中的商品
        //不穿或者传递一个空值，则显示所有商品
      };

      query.classify_id && (where.classify_id = query.classify_id);
      query.name && (where.name = { [Op.like]: `%${query.name}%` });
      where.project_id =
        query.project_id ||
        (this.ctx.adminInfo && this.ctx.adminInfo.project_id);

      if (!where.project_id) return this.ctx.response.lack('project_id');

      // findAndCountAll - 搜索数据库中多个元素，同时返回数据和总数
      const result = await Goods.findAndCountAll({
        limit,
        offset,
        order: [['createdAt', 'DESC']],
        where,
        include: [
          {
            // 需要的字段
            attributes: ['id', 'path'],
            // 链接的表
            model: GoodsPhoto,
            // required: false,
            where: {
              type: 1,
            },
          },
          {
            // 需要的字段
            attributes: ['id', 'name'],
            // 链接的表
            model: Classify,
            // required: false,
            // where: {
            //   type: 1
            // },
          },
        ],
        distinct: true,
      });

      if (result) {
        // 更改格式返回
        return this.ctx.response.success(result);

        // const data = JSON.parse(JSON.stringify(result));
        // return this.ctx.response.success({
        //   count: data.count,
        //   rows: data.rows.map(res => {
        //     if (res.s_photos.length) {
        //       res.s_photos.map(r => {
        //         r.path = ('http://' + this.ctx.request.header.host + r.path).replace(/\\/g, '/');
        //       });
        //     }
        //     return res;
        //   }),
        // });
      }
      return this.ctx.response.error('获得商品列表信息失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  //获取总销售额
  async getAllNum() {
    try {
      const { Order } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      const default_start = '1970-01-01';
      const default_end = '9999-12-31';
      let start = query.start || default_start;
      let end = query.end || default_end;
      const where = {
        createdAt: {
          [Op.between]: [start, end],
        },
      };
      where.project_id =
        query.project_id ||
        (this.ctx.adminInfo && this.ctx.adminInfo.project_id);
      const result = await Order.findAll({
        where,
        attributes: {
          exclude: ['goods_info', 'createdAt', 'updatedAt'],
        },
      });
      if (result) {
        return this.ctx.response.success(result);
      } else {
        return this.ctx.response.success(0);
      }
    } catch (error) {
      return this.ctx.response.error(
        `获取总销售额失败，失败原因${error.message}`
      );
    }
  }
  //获取所有商品的销售量
  async getSoldNum() {
    try {
      const { Goods, Classify } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      const where = {
        parent_id: 0,
      };
      where.project_id =
        query.project_id ||
        (this.ctx.adminInfo && this.ctx.adminInfo.project_id);
      const result = await Classify.findAndCountAll({
        // where: {
        //   classify_id,
        // },
        where,
        // where: {
        //   parent_id: 0
        // },
        attributes: {
          exclude: ['sort', 'thumb_url', 'path', 'createdAt', 'updatedAt'],
        },
        include: [
          {
            // 需要的字段
            attributes: ['id', 'name', 'sold_num'],
            // 链接的表
            model: Goods,
            // required: false,
          },
        ],
        distinct: true,
      });
      // console.log('这里是该类的销售总量===>', sold_total);
      //返回给前端的数据简单化 仅返回销售数量和查询的id
      if (result) {
        // let sold_list = result.rows
        // //统计该类商品的总销售数量
        // let sold_total = sold_list.reduce((sum, e) => sum + e.sold_num, 0)
        // console.log('==============>result_num', result);
        const data = JSON.parse(JSON.stringify(result));
        // console.log('====>', data);
        data.rows.forEach((ele) => {
          let sold_list = ele.s_goods;
          let sold_total = sold_list.reduce((sum, e) => sum + e.sold_num, 0);
          ele.sold_total = sold_total;
        });
        // console.log(data);
        return this.ctx.response.success(data.rows.slice(0, 10));
      }
      return this.ctx.response.error('找不到该类商品信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }

  // 获取热门商品
  async hotGoods() {
    try {
      const { Goods, GoodsPhoto } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      // 每页多少条
      const limit = parseInt(query.limit) || 10;
      // 页数
      const page = parseInt(query.page) || 1;
      // 页数 * 每页个数
      const offset = limit * (page - 1);
      const where = {
        status: 1,
      };

      where.project_id =
        query.project_id ||
        (this.ctx.adminInfo && this.ctx.adminInfo.project_id);
      if (!where.project_id) return this.ctx.response.lack('project_id');

      const result = await Goods.findAndCountAll({
        limit,
        offset,
        order: [['sold_num', 'DESC']],
        where,
        include: [
          {
            // 需要的字段
            attributes: ['id', 'path'],
            // 链接的表
            model: GoodsPhoto,
            where: {
              type: 1,
            },
          },
        ],
        // 独特的数据 联表查询统计数量不会增加图片表的数量
        distinct: true,
      });

      if (result) {
        // 更改格式返回
        return this.ctx.response.success(result);
        // const data = JSON.parse(JSON.stringify(result));
        // return this.ctx.response.success({
        //   count: data.count,
        //   rows: data.rows.map(res => {
        //     if (res.s_photos.length) {
        //       res.s_photos.map(r => {
        //         r.path = ('http://' + this.ctx.request.header.host + r.path).replace(/\\/g, '/');
        //       });
        //     }
        //     return res;
        //   }),
        // });
      }
      return this.ctx.response.error('获取热门商品列表信息失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  //搜索商品
  async search() {
    try {
      const { Goods, GoodsPhoto } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      const where = {
        status: 1,
      };
      const limit = parseInt(query.limit) || 10;
      const offset = parseInt(query.offset) || 0;
      query.name && (where.name = { [Op.like]: `%${query.name}%` });
      //在数据库中模糊查询前端传来的字段
      where.project_id =
        query.project_id ||
        (this.ctx.adminInfo && this.ctx.adminInfo.project_id);
      const resultGoods = await Goods.findAndCountAll({
        order: [['createdAt', 'DESC']],
        where,
        limit,
        offset,
        include: [
          {
            // 需要的字段
            attributes: ['id', 'path'],
            // 链接的表
            model: GoodsPhoto,
            // required: false,
            where: {
              type: 1,
            },
          },
        ],
        distinct: true,
      });
      let i = 0;
      let search_list = resultGoods.rows; //查询到的数据存到数组中
      // console.log('这里是searchlist=>>>>>>>>>>>', search_list);
      while (search_list[i]) {
        //将数组中每个商品的search_num+1
        await search_list[i].update({
          id: search_list[i].dataValues.id,
          search_num: search_list[i].dataValues.search_num + 1,
        });
        i++;
      }
      if (resultGoods) {
        // 更改格式返回
        return this.ctx.response.success(resultGoods);
      }
      return this.ctx.response.error('查询商品信息失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 获取单个商品信息
  async show(id) {
    try {
      const { Goods, GoodsPhoto } = this.app.model.Tables.Shop;
      const { Admin } = this.app.model.Tables.Com;
      const result = await Goods.findOne({
        where: {
          id,
        },
        include: [
          {
            // 需要的字段
            attributes: ['id', 'path'],
            model: GoodsPhoto,
            // required: false,
            where: {
              type: 1,
            },
          },
          {
            model: Admin,
            attributes: ['id', 'project_id', 'name'],
          },
        ],
      });
      if (result) {
        return this.ctx.response.success(result);
      }
      return this.ctx.response.error('找不到该商品信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 更新商品信息
  async update(id, data) {
    const { ctx, service } = this;
    try {
      const { Goods } = this.app.model.Tables.Shop;
      // 获取所有的classify_ids
      let classifyArr = String(data.classify_id);
      // 设置最后一个就是最终选择的

      data.classify_id =
        String(data.classify_id).length > 0 &&
        String(data.classify_id).split(',')[
          String(data.classify_id).split(',').length - 1
        ];

      const resultGoods = await Goods.findOne({
        where: {
          id,
          shops_id: ctx.adminInfo.id,
        },
      });

      if (resultGoods) {
        const resultG = await resultGoods.update({
          ...data,
          classify_ids: classifyArr,
        });

        await service.shop.goodsPhoto.update(
          resultGoods.dataValues.id,
          data.photo_ids,
          1
        );
        return resultG
          ? ctx.response.success(resultG, '更新成功')
          : ctx.response.error(resultG, '更新失败');
      }
      return ctx.response.error('找不到该商品信息');
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }
  // 添加商品
  async create(dataObj) {
    const { ctx, service } = this;
    const { Goods } = this.app.model.Tables.Shop;
    let userData = ctx.adminInfo || ctx.userInfo;

    try {
      dataObj = {
        ...dataObj,
        shops_id: userData.id,
        project_id: userData.project_id,
        classify_id:
          dataObj.classify_id.split(',')[
            dataObj.classify_id.split(',').length - 1
          ],
        classify_ids: dataObj.classify_id,
      };

      const result = await Goods.create(dataObj);
      const photoResult = await service.shop.goodsPhoto.update(
        result.dataValues.id,
        dataObj.photo_ids,
        1
      );

      return result && photoResult
        ? ctx.response.success('添加成功')
        : ctx.response.error(result, '添加失败');
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }
  // 删除商品
  async destroy(id) {
    const { ctx } = this;
    try {
      const { Goods } = this.app.model.Tables.Shop;
      const resultGoods = await Goods.destroy({
        where: {
          id,
          shops_id: ctx.adminInfo.id,
        },
      });
      return resultGoods > 0
        ? ctx.response.success('删除成功')
        : ctx.response.error('删除失败');
      // if (resultGoods) {
      //   // const resultG = await resultGoods.update({ status: '2' });
      //   return resultG ? (ctx.response.success('删除成功')) : (ctx.response.error(resultG, '更新失败'));
      // }
      // return ctx.response.error('找不到该商品信息');
      // return result > 0 ? (ctx.response.success('删除成功')) : (ctx.response.error('删除失败'));
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '已有该商品名称' : error.message
      );
    }
  }

  async getByClassifyId(classify_id) {
    const { ctx, app } = this;
    const { Goods, GoodsPhoto } = app.model.Tables.Shop;

    try {
      const goodsResult = await Goods.findAll({
        where: {
          classify_id,
        },
        include: [
          {
            // 需要的字段
            attributes: ['id', 'path'],
            model: GoodsPhoto,
          },
        ],
      });

      return ctx.response.success(goodsResult);
    } catch (error) {
      return ctx.response.error(
        error.message === 'Validation error' ? '不存在该分类' : error.message
      );
    }
  }
}

module.exports = GoodsService;
